package com.tanhua.dubbo.api.impl;


import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.pojo.RecommendSound;
import com.tanhua.dubbo.pojo.Sound;
import com.tanhua.dubbo.service.IdService;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


@DubboService(version = "1.0.0")
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Sound sound) {
        sound.setId(ObjectId.get());
        this.mongoTemplate.save(sound);
    }

    /**
     * 查询推荐的语音
     * @param userId
     * @return
     */
    @Override
    public Sound getHighScoreSound(Long userId) {
        //推荐的语音列表
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("state").is(0)).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        RecommendSound recommendSound = this.mongoTemplate.findOne(query, RecommendSound.class);
        if (ObjectUtil.isEmpty(recommendSound)){
            return null;
        }

        Sound sound = new Sound();
        if (ObjectUtil.isNotEmpty(sound)){
            sound = getSound(recommendSound.getVoiceId());
            Update update = new Update().set("state",1);
            ObjectId voiceId = recommendSound.getVoiceId();
            Query queryUpdate = Query.query(Criteria.where("voiceId").is(voiceId));
            this.mongoTemplate.updateFirst(queryUpdate, update, RecommendSound.class);
        }
        return sound;
    }

    /**
     * 查询用户的语音
     * @param voiceId
     * @return
     */
    @Override
    public Sound getSound(ObjectId voiceId) {
        Query query = Query.query(Criteria.where("_id").is(voiceId));
        Sound sound = this.mongoTemplate.findOne(query, Sound.class);
        return sound;
    }

}
